
package com.kugou.game.sdk.ui.activity;

import com.kugou.framework.v4.FragmentTransaction;
import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.BaseSDKConfig;
import com.kugou.game.sdk.api.common.IEventCode;
import com.kugou.game.sdk.api.common.IEventDataField;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.core.PayManager;
import com.kugou.game.sdk.core.PlatformEventDispatcher;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.core.VipManager;
import com.kugou.game.sdk.entity.PayConstant;
import com.kugou.game.sdk.entity.PayConstant.ChargeIndexMode;
import com.kugou.game.sdk.interfaces.OnRegisterListener;
import com.kugou.game.sdk.interfaces.OnRequestVipInfoListener;
import com.kugou.game.sdk.statistics.StatCmd;
import com.kugou.game.sdk.statistics.StaticsManager;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.ui.fragment.BaseRechargeFragment;
import com.kugou.game.sdk.ui.fragment.CheckRechargeResultFragment;
import com.kugou.game.sdk.ui.fragment.RechargeByAliPayFragment;
import com.kugou.game.sdk.ui.fragment.RechargeByGameCardFragment;
import com.kugou.game.sdk.ui.fragment.RechargeByKuBiFragment;
import com.kugou.game.sdk.ui.fragment.RechargeByMobileCardFragment;
import com.kugou.game.sdk.ui.fragment.RechargeBySMSFragment;
import com.kugou.game.sdk.ui.fragment.RechargeByUnionFragment;
import com.kugou.game.sdk.ui.fragment.RechargeByWeixinFragment;
import com.kugou.game.sdk.ui.fragment.RechargeSelectModeFragment;
import com.kugou.game.sdk.ui.fragment.RechargeSelectModeFragment.OnModeSelectedListener;
import com.kugou.game.sdk.ui.fragment.RechargeSuccessFragment;
import com.kugou.game.sdk.ui.widget.HelpMenuPopupWindow;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.NetWorkUtil;
import com.kugou.game.sdk.utils.Rx;
import com.kugou.game.sdk.utils.ToastUtil;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.View;

import java.util.ArrayList;

/**
 * 描述:充值界面Activity
 *
 * @author wcj
 * @since 2015年11月11日 上午10:56:44
 */
public class RechargeActivity extends BaseCommonTitleFragmentActivity {

    public static final String FIXED_MONEY_NUM = "fixed_money_num";

    public static final String IS_RECHARGE_YOUBI = "is_recharge_youbi";

    public static final String SOURCE_FROM = "sourc_from";

    private final int MSG_REQUEST_AUTO_REGISTER = 0X0A3;

    private final int MSG_REQUEST_AUTO_REGISTER_SUCCESS = 0X0A4;

    private final int MSG_REQUEST_AUTO_REGISTER_FAILED = 0X0A5;

    private final int MSG_BACK_REQUEST_VIP_INFO = 0X0A6;

    // 是否充值游币
    private boolean mIsRechargeYoubi = false;

    RechargeByAliPayFragment mRechargeByAliPayFragment;

    RechargeByWeixinFragment mRechargeByWeixinFragment;

    RechargeByUnionFragment mRechargeByUnionFragment;

    RechargeByMobileCardFragment mRechargeByMobileCardFragment;

    RechargeByKuBiFragment mRechargeByKuBiFragment;

    RechargeByGameCardFragment mRechargeByGameCardFragment;

    RechargeBySMSFragment mRechargeBySMSFragment;

    RechargeSelectModeFragment mRechargeSelectModeFragment;

    private int mCurrentTabIndex = 0;

    /**
     * 固定金额
     */
    private int mFixedMoneyNum;

    // 是否定额充值界面
    private boolean mIsFixedPage;

    private boolean mIsInRechargePage;

    private ProgressDialog mDialog;

    private boolean mIsRechargeCheckingResult = false;

    private int mSourceFrom = 0;

    /**
     * 跳转到游戏充值界面
     * 
     * @param context
     * @param sourceFrom 进入充值游币来源，用于统计。1：用户中心-充值按钮2：用户中心-banner3：游戏支付活动 4：sdk
     *            h5活动页banner5:用户中心-成为vip按钮6:代金券页面-限游币充值代金券
     */
    public static void showYoubiRechargePage(Context context, int sourceFrom) {
        Intent intent = new Intent(context, RechargeActivity.class);
        intent.putExtra(RechargeActivity.IS_RECHARGE_YOUBI, true);
        intent.putExtra(RechargeActivity.SOURCE_FROM, sourceFrom);
        context.startActivity(intent);
    }

    public boolean isRechargeYoubi() {
        return mIsRechargeYoubi;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int layoutId = Rx.layout.kg_homerecharge_activity;
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            layoutId = Rx.layout.kg_homerecharge_activity_land;
        }

        getWindow().getDecorView().setLayerType(View.LAYER_TYPE_SOFTWARE, null);

        setContentView(layoutId);

        mFixedMoneyNum = getIntent().getIntExtra(RechargeActivity.FIXED_MONEY_NUM, -1);
        mIsRechargeYoubi = getIntent().getBooleanExtra(RechargeActivity.IS_RECHARGE_YOUBI, false);
        mSourceFrom = getIntent().getIntExtra(RechargeActivity.SOURCE_FROM, 0);
        mIsFixedPage = (mFixedMoneyNum > 0);

        // 检测账号信息
        User user = UserManager.getInstance().getCurrentUserInternal();
        if (user != null) {// 内存存在登录信息
            if (!user.isRegistered()) {// 游客登录
                if (NetWorkUtil.isNetworkAvailable(this)) {
                    mDialog = new ProgressDialog(this);
                    mDialog.setCanceledOnTouchOutside(false);
                    mDialog.setCancelable(false);
                    mDialog.setMessage("正在检测支付安全环境，请稍候...");
                    mDialog.show();
                    // 请求自动注册
                    sendEmptyBackgroundMessage(MSG_REQUEST_AUTO_REGISTER);
                    return;
                } else {
                    enterRegisterActivity();
                }
            }
        } else {
            enterRegisterActivity();
        }

        initView();

        // 每次进入充值界面去请求充值兑换比例
        PayManager.requestExchangeRatio();
        PayManager.requestCouponInfo(mIsRechargeYoubi, null);

        // 每次进入充值界面刷新酷币余额，保证余额实时更新
        UserManager.getInstance().updateYoubiNum();

    }

    private void initView() {
        initFragment();

        if (mIsRechargeYoubi) {
            setCommonTitle("游币充值");
        } else {
            setCommonTitle(Rx.string.kg_kugou_recharge_center);
        }

        int lastPayModeTab = PayManager.getLastRechargeMode();
        // 充值卡、游戏点卡、短信支付没有定额充值，所以不使用记忆的充值方式，使用默认支付宝方式
        // 游币支付，不需要显示游币支付界面
        if (lastPayModeTab < 0
                || (mIsFixedPage && (lastPayModeTab == PayConstant.ChargeIndexMode.MODE_MOBILE_CARD
                        || lastPayModeTab == PayConstant.ChargeIndexMode.MODE_MOBILE_CARD
                        || lastPayModeTab == PayConstant.ChargeIndexMode.MODE_GAME_CARD || lastPayModeTab == PayConstant.ChargeIndexMode.MODE_SMS))
                || (lastPayModeTab == PayConstant.ChargeIndexMode.MODE_YOUBI && mIsRechargeYoubi)) {
            showSelectModeView();
        } else {
            showSelectedTab(lastPayModeTab);
        }
    }

    private void initFragment() {
        mRechargeByAliPayFragment = RechargeByAliPayFragment.getInstance(mFixedMoneyNum,
                mIsRechargeYoubi);
        mRechargeByWeixinFragment = RechargeByWeixinFragment.getInstance(mFixedMoneyNum,
                mIsRechargeYoubi);
        mRechargeByUnionFragment = RechargeByUnionFragment.getInstance(mFixedMoneyNum,
                mIsRechargeYoubi);
        mRechargeByKuBiFragment = RechargeByKuBiFragment.getFragment(mFixedMoneyNum);
        mRechargeByGameCardFragment = RechargeByGameCardFragment.getFragment(mIsRechargeYoubi);
        mRechargeByMobileCardFragment = RechargeByMobileCardFragment.getFragment(mIsRechargeYoubi);
        mRechargeBySMSFragment = RechargeBySMSFragment.getInstance(mIsRechargeYoubi);

        boolean showRecommond = false;
        // 如果定额支付定额小于余额，或者普通支付余额大于0，则显示推荐模式
        if ((mIsFixedPage && mFixedMoneyNum <= UserManager.getInstance().getCurrentUserInternal()
                .getKubiNum())
                || (!mIsFixedPage && UserManager.getInstance().getCurrentUserInternal()
                        .getKubiNum() > 0)) {
            showRecommond = true;
        }
        mRechargeSelectModeFragment = RechargeSelectModeFragment.getFragment(showRecommond,
                mFixedMoneyNum, mIsRechargeYoubi);
        mRechargeSelectModeFragment.setModeSelectedListener(new OnModeSelectedListener() {

            @Override
            public void onSeleced(int mode) {
                showSelectedTab(mode);
                if (mode == ChargeIndexMode.MODE_YOUBI && PayManager.isShowRedPoint()) {
                    PayManager.changeShowRedPoint(false);
                }
                // 发送统计--选择充值方式
                StaticsManager.sendRechargeTypeStatics(StatCmd.CMD_SELECT_RECHARGE_MODE,
                        mIsRechargeYoubi ? 1 : 2, PayConstant.swapRechargeMode(mode));
            }
        });

        mRechargeByAliPayFragment.setOnEventListener(mEventListener);
        mRechargeByWeixinFragment.setOnEventListener(mEventListener);
        mRechargeByUnionFragment.setOnEventListener(mEventListener);
        mRechargeByMobileCardFragment.setOnEventListener(mEventListener);
        mRechargeByKuBiFragment.setOnEventListener(mEventListener);
        mRechargeByGameCardFragment.setOnEventListener(mEventListener);
        mRechargeBySMSFragment.setOnEventListener(mEventListener);
    }

    BaseRechargeFragment.OnEventListener mEventListener = new BaseRechargeFragment.OnEventListener() {

        @Override
        public void onChangeRechargeMode() {
            showSelectModeView();
        }

        @Override
        public void onRechargeSuccess(int mode, int value) {
            if (mIsRechargeYoubi) {
                showYoubiRechargeSuccess(mode, value);
            } else {
                showGameRechargeSuccess(mode);
            }
            PayManager.setLastRechargeMode(mode);

            getHelpMenuPopupWindow().hideRechargeTipsItem();
            mIsInRechargePage = false;
            sendEmptyBackgroundMessage(MSG_BACK_REQUEST_VIP_INFO);
        }

        @Override
        public void onRechargeResultChange(boolean isChecking) {
            showRechargeMobileResult(isChecking);
        }

        @Override
        public void onCheckRechargeResult(String order, int value, int mode) {
            showCheckRechargeResultView(order, value, mode);

            getHelpMenuPopupWindow().hideRechargeTipsItem();
            mIsInRechargePage = false;
        }
    };

    private void showSelectModeView() {
        hideSoftInput(RechargeActivity.this);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(Rx.id.kg_recharge_pager, mRechargeSelectModeFragment);
        transaction.commitAllowingStateLoss();

        getHelpMenuPopupWindow().hideRechargeTipsItem();
        mIsInRechargePage = false;

        // 发送统计-进入充值选择列表页面
        StaticsManager.sendEnterRechargeListStatics(mIsRechargeYoubi ? 1 : 2, mSourceFrom);
        mSourceFrom = 0;
    }

    private void showCheckRechargeResultView(String order, int value, int mode) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        CheckRechargeResultFragment fragment = CheckRechargeResultFragment.getFragment(order,
                value, mode);
        fragment.setOnEventListener(mEventListener);
        transaction.replace(Rx.id.kg_recharge_pager, fragment);
        transaction.commitAllowingStateLoss();
    }

    private void showSelectedTab(int index) {
        mCurrentTabIndex = index;

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        if (mCurrentTabIndex == ChargeIndexMode.MODE_ALIPAY) {
            transaction.replace(Rx.id.kg_recharge_pager, mRechargeByAliPayFragment);
        } else if (mCurrentTabIndex == ChargeIndexMode.MODE_UNION) {
            transaction.replace(Rx.id.kg_recharge_pager, mRechargeByUnionFragment);
        } else if (mCurrentTabIndex == ChargeIndexMode.MODE_MOBILE_CARD) {
            transaction.replace(Rx.id.kg_recharge_pager, mRechargeByMobileCardFragment);
        } else if (mCurrentTabIndex == ChargeIndexMode.MODE_YOUBI) {
            transaction.replace(Rx.id.kg_recharge_pager, mRechargeByKuBiFragment);
        } else if (mCurrentTabIndex == ChargeIndexMode.MODE_GAME_CARD) {
            transaction.replace(Rx.id.kg_recharge_pager, mRechargeByGameCardFragment);
        } else if (mCurrentTabIndex == ChargeIndexMode.MODE_SMS) {
            transaction.replace(Rx.id.kg_recharge_pager, mRechargeBySMSFragment);
        } else if (mCurrentTabIndex == ChargeIndexMode.MODE_WEIXIN) {
            transaction.replace(Rx.id.kg_recharge_pager, mRechargeByWeixinFragment);
        }

        transaction.commitAllowingStateLoss();

        // 发送统计--进入具体充值方式
        StaticsManager.sendRechargeTypeStatics(StatCmd.CMD_ENTER_RECHARGE_DETAIL_PAGE,
                mIsRechargeYoubi ? 1 : 2, PayConstant.swapRechargeMode(index));

        getHelpMenuPopupWindow().showRechargeTipsItem();
        mIsInRechargePage = true;
    }

    private void enterRegisterActivity() {
        showToast("为了您充值安全，请先注册成正式账号");
        // 进入注册页面
        Intent intent = new Intent(this, RegisterByPhoneActivity.class);
        intent.putExtra(FROM_ACTION_KEY, FROM_RECHARGE);
        intent.putExtra(FIXED_MONEY_NUM, getIntent().getIntExtra(FIXED_MONEY_NUM, -1));
        startActivity(intent);
        finish();
    }

    // 显示游戏充值成功界面
    public void showGameRechargeSuccess(int mode) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(Rx.id.kg_recharge_pager, RechargeSuccessFragment.getFragment());
        transaction.commitAllowingStateLoss();

        mIsRechargeCheckingResult = false;

    }

    // 显示游币充值成功界面
    private void showYoubiRechargeSuccess(int rechargeMode, int mRechargeValue) {

        rechargeMode = PayConstant.swapRechargeMode(rechargeMode);

        // 充值卡的扣除手续费
        float rechargeValue = (float) (PayManager.getExchangeRatio(rechargeMode, mRechargeValue) * mRechargeValue);
        // 加上充值优惠
        rechargeValue = rechargeValue * PayManager.getYoubiRatio()
                + PayManager.getExchangeKubiExtraNum(mRechargeValue);

        UserManager.getInstance().updateYoubiNum();

        startActivity(KubiRechargeSuccessActivity.createIntent(this, rechargeValue));
        finish();

    }

    public void showRechargeMobileResult(boolean isChecking) {
        if (isChecking) {
            // 隐藏titil返回按钮
            setCommonLeftImageViewVisibility(View.INVISIBLE);
            mIsRechargeCheckingResult = true;
        } else {
            setCommonLeftImageViewVisibility(View.VISIBLE);
            mIsRechargeCheckingResult = false;
        }
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        super.handleBackgroundMessage(msg);
        switch (msg.what) {
            case MSG_REQUEST_AUTO_REGISTER:
                final Message message = new Message();
                // 获取注册请求相关参数
                String tempName;
                User userData = UserManager.getInstance().getCurrentUserInternal();
                if (userData != null && !userData.isRegistered()) {
                    tempName = userData.getOpenId();
                } else {
                    tempName = "";
                    message.what = MSG_REQUEST_AUTO_REGISTER_FAILED;
                    message.obj = "请先登录后再进入充值界面";
                    sendUiMessage(message);
                    return;
                }
                // 发送注册请求
                UserManager.getInstance().registerByAuto(tempName, new OnRegisterListener() {
                    @Override
                    public void onSuccess(User newUser) {
                        if (SDKControler.getGameType() == BaseSDKConfig.GAME_TYPE_ONLINE) {
                            AppUtil.writeDataToSSO(newUser);
                        }
                        message.what = MSG_REQUEST_AUTO_REGISTER_SUCCESS;
                        message.obj = newUser;
                    }

                    @Override
                    public void onFailed(String errorMsg, String errorCode) {
                        message.what = MSG_REQUEST_AUTO_REGISTER_FAILED;
                        message.obj = errorMsg;
                    }

                    @Override
                    public void onRecommendRegisterName(ArrayList<String> names) {
                    }
                });
                sendUiMessage(message);
                break;
            case MSG_BACK_REQUEST_VIP_INFO:
                if (!VipManager.getInstance().isVip()) {
                    VipManager.getInstance().requestVipInfos(true, new OnRequestVipInfoListener() {

                        @Override
                        public void onSuccess() {
                            // VipManager.getInstance().getVipInfo().setVip(true);
                            if (VipManager.getInstance().isVip()) {
                                mContext.sendBroadcast(new Intent(SDKActions.ACTION_CHANGE_TO_VIP));
                            }
                        }

                        @Override
                        public void onFail() {
                            // TODO Auto-generated method stub

                        }
                    });
                }
                break;
        }
    }

    @Override
    public void handleUiMessage(Message msg) {
        if (isFinishing()) {
            return;
        }

        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
            mDialog = null;
        }

        super.handleUiMessage(msg);
        switch (msg.what) {
            case MSG_REQUEST_AUTO_REGISTER_FAILED:
                enterRegisterActivity();
                break;
            case MSG_REQUEST_AUTO_REGISTER_SUCCESS:
                // 发送注册成功回调事件
                Bundle bundle = new Bundle();
                User newUser = (User) msg.obj;
                bundle.putSerializable(IEventDataField.EXTRA_USER, newUser);
                PlatformEventDispatcher.sendEvent(IEventCode.REGISTER_SUCCESS, bundle);
                AppUtil.handleActionsAfterLoginSuccess(IEventCode.REGISTER_SUCCESS);
                // 设置提醒修改密码
                UserManager.getInstance().getCurrentUserInternal().setNeedRemindModifyPsd(true);
                initView();
                sendBroadcast(new Intent(SDKActions.ACTION_AUTO_REGISTER_SUCCESS));
                break;
        }
    }

    @Override
    public void onBackPressed() {

        if (mIsRechargeCheckingResult) {
            ToastUtil.showMsg("正在查询充值结果...");
            return;
        }

        if (mIsInRechargePage) {
            showSelectModeView();
            return;
        }

        super.onBackPressed();
    }

    /**
     * 调用该方法就表示是：定额支付
     * 
     * @param context
     * @param moneyNum
     * @return
     */
    public static Intent createIntent(Context context, int moneyNum) {
        Intent intent = new Intent(context, RechargeActivity.class);
        intent.putExtra(FIXED_MONEY_NUM, moneyNum);
        return intent;
    }

    /**
     * 帮助按钮为3个item
     */
    @Override
    protected int initMenuItemNums() {
        return HelpMenuPopupWindow.HELP_MENU_ITEM_COUNT_FOUR;
    }

    @Override
    protected void onTipsDialogShow(BaseConfirmDialog dialog, int position) {
        if (position != 3)
            return;

        if (mCurrentTabIndex == ChargeIndexMode.MODE_MOBILE_CARD) {
            dialog.setMessage(getResources().getString(Rx.string.kg_recharge_mobile_tips));
        } else if (mCurrentTabIndex == ChargeIndexMode.MODE_ALIPAY
                || mCurrentTabIndex == ChargeIndexMode.MODE_UNION
                || mCurrentTabIndex == ChargeIndexMode.MODE_WEIXIN) {
            dialog.setMessage(mContext.getResources().getString(Rx.string.kg_recharge_tips));
        } else if (mCurrentTabIndex == ChargeIndexMode.MODE_YOUBI) {
            dialog.setMessage(getResources().getString(Rx.string.kg_recharge_youbi_tips));
        } else if (mCurrentTabIndex == ChargeIndexMode.MODE_GAME_CARD) {
            dialog.setMessage(getResources().getString(Rx.string.kg_recharge_game_card_tips));
        } else if (mCurrentTabIndex == ChargeIndexMode.MODE_SMS) {
            dialog.setMessage(getResources().getString(Rx.string.kg_recharge_sms_tips));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 微信支付通过该方式获取回调
        if (mCurrentTabIndex == ChargeIndexMode.MODE_WEIXIN) {
            if (mRechargeByWeixinFragment != null) {
                mRechargeByWeixinFragment.onActivityResult(requestCode, resultCode, data);
            }
        }
    }
}
